//
//  LoopPictureCollectionView.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/11.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit

let picCellId = "LoopPictureCollectionViewCell"
class LoopPictureCollectionView: UICollectionView,UICollectionViewDataSource,UICollectionViewDelegate,SDPhotoBrowserDelegate {

    var pictureInfo:[LoopHomePicture]?{
        didSet{
//            print(pictureInfo)
        self.reloadData()
        }
    }
    override func awakeFromNib() {
        //注册cell
        let picCell = UINib(nibName: "LoopPictureCollectionViewCell", bundle: nil)
        self.register(picCell, forCellWithReuseIdentifier: picCellId)
        self.isScrollEnabled = false
        self.dataSource = self
        self.delegate = self
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        print(pictureInfo?.count ?? 0)
        return pictureInfo?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: picCellId, for: indexPath) as! LoopPictureCollectionViewCell
        let picInfo = pictureInfo![indexPath.item]
        cell.picInfo = picInfo
        return cell
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        /*
         - (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index;
         
         @optional
         
         - (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index;
         
         @end
         
         
         @interface SDPhotoBrowser : UIView <UIScrollViewDelegate>
         
         @property (nonatomic, weak) UIView *sourceImagesContainerView;
         @property (nonatomic, assign) NSInteger currentImageIndex;
         @property (nonatomic, assign) NSInteger imageCount;
         
         @property (nonatomic, weak) id<SDPhotoBrowserDelegate> delegate;
         
         - (void)show;

         */
        
        let bowser = SDPhotoBrowser()
        bowser.sourceImagesContainerView = self
        bowser.currentImageIndex = indexPath.item
        bowser.imageCount = pictureInfo?.count ?? 0
        bowser.delegate = self
        
        bowser.show()
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        
        let picInfo = pictureInfo?[index]
        let url = URL(string: picInfo?.bmiddle_pic ?? "")
        return url
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        let indexPath = IndexPath(item: index, section: 0)
        let cell = cellForItem(at: indexPath) as? LoopPictureCollectionViewCell
        return cell!.imgPic.image
    }
    

}
